package com.gemantic.task.config;


import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author xiedi
 * @date 2022/09/16
 **/
@Configuration
public class ThreadPoolConfig {
    public static final String THREAD_POOL_NAME = "taskExecutor";
    private static final int MAX_POOL_SIZE = 50;

    @Value("${thread.corePoolSize:20}")
    private Integer threadCorePoolSize;

    @Value("${thread.queueCapacity:-1}")
    private Integer threadQueueCapacity;


    /**
     * 默认注入一个线程池
     *
     * @return ThreadPoolTaskExecutor
     */
    @Bean(THREAD_POOL_NAME)
    public ThreadPoolTaskExecutor taskExecutorInit() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        threadQueueCapacity = threadQueueCapacity > -1 ? threadQueueCapacity : threadCorePoolSize * MAX_POOL_SIZE;

        taskExecutor.setCorePoolSize(threadCorePoolSize);
        taskExecutor.setQueueCapacity(threadCorePoolSize * MAX_POOL_SIZE);
        taskExecutor.setMaxPoolSize(threadCorePoolSize + MAX_POOL_SIZE);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return taskExecutor;
    }


}
